package com.mgq.algorithm.graph;

import java.util.HashSet;
import java.util.Stack;

/**
 * @author MaGuangQi
 * 深度优先遍历 DFS
 * @date 2022-01-03 21:45
 **/
public class DFS {

    /**
     * 图的深度遍历
     */
    public void dfs(Node node) {
        Stack<Node> stack = new Stack<>();
        HashSet<Node> set = new HashSet<>();
        stack.push(node);
        set.add(node);
        System.out.println(node.value);
        while (!stack.isEmpty()) {
            Node cur = stack.pop();
            for (Node next : cur.nexts) {
                if (!set.contains(next)) {
                    //把node重新压入栈
                    stack.push(cur);
                    //再把next压入
                    stack.push(next);
                    set.add(next);
                    System.out.println(next.value);
                    //某个节点的第一个next不在set中时,把cur和next都加入,然后终止循环
                    break;
                }
            }
        }
    }
}
